<?php

namespace IDock\Insurance\HBIC\Request;

use IDock\Insurance\DAJIA\Response\InsuranceOrderQueryResponse;
use IDock\Insurance\HBIC\Bean\BASEPART;
use IDock\Insurance\HBIC\Bean\CAR;
use IDock\Insurance\HBIC\Bean\CARSHIPTAX;
use IDock\Insurance\HBIC\Bean\DEVICE;
use IDock\Insurance\HBIC\Bean\KIND;
use IDock\Insurance\HBIC\Bean\NOCAR;
use IDock\Insurance\HBIC\Bean\PERSONNEL;
use IDock\Insurance\HBIC\HBICEnums;
use IDock\Insurance\HBIC\Response\CommonResponse;
use IDock\Insurance\HBIC\Response\InsurancePriceQueryResponse;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

class InsuranceOrderPriceRequest extends AllHBICRequest
{
    public $requestType = 'A01';

    protected $response = InsurancePriceQueryResponse::class;

    protected $urlTip = '保费计算';

    protected $resourceType = 'BXT';

    protected $methodName = 'premiumCalculate';

    public $userCode;

    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {
        $param = [
            'resourceType' => $this->resourceType,
            'methodName' => $this->methodName,
            'BASE_PART' => $this->getBasePart(),
            'CAR' => $this->getVehicleInfo(),
            'KIND_LIST' => ['KIND' => $this->getKindList()],
            'CARSHIPTAX' => $this->getCarShipTax(),
            'PERSONNEL' => $this->getPerson(),
            'DEVICELIST' => [],
//            'CHARGINGPOSTLIST' => $this->getChargeList(),
//            'INSUREDLIST' => json_decode(json_encode($this->INSUREDLIST), true),
//            'NOCAR' => json_decode(json_encode($this->NOCAR), true),
        ];
        if(!empty($this->visitor->getChargingPileVisitorList())){
            $param['CHARGINGPOSTLIST'] = $this->getChargeList();
        }
        foreach ($param as $key => $val) {
            if (empty($val)) {
                unset($param[$key]);
            }
        }

        return $param;
    }

    public function getBasePart()
    {
        $basePart = [
            'RISKTYPE' => $this->getInsuranceType(),//0-单商业，1-单交强，2-关联出单
            'STARTDATEBI' => $this->visitor->biStartData,//商业险起保日期
            'STARTDATECI' => $this->visitor->ciStartData,//交强险起保日期
            'ENDDATEBI' => $this->visitor->biEndData,//商业险终保日期
            'ENDDATECI' => $this->visitor->ciEndData,//交强险终保日期
            'INPUTSYSCODE' => $this->visitor->getExtInfoVisitor()->argc['INPUTSYSCODE'] ?? '',//业务渠道代码
            'AREACODE' => $this->visitor->getOwnerVisitor()->provinceCode,//投保地区 四川
            'PACKAGECODE' => $this->visitor->getExtInfoVisitor()->argc['PACKAGECODE'] ?? '',
            'USERCODE' => $this->userCode,
            'INSUREDNAME' => $this->visitor->getInsuredVisitor()->name,//被保险人名字
            'COMPANYCODE' => $this->visitor->getExtInfoVisitor()->argc['COMPANYCODE'] ?? '',//业务归属机构
            'AGREEMENTNO' => $this->visitor->getExtInfoVisitor()->argc['AGREEMENTNO'] ?? '',//中介协议号
            'INTERMEDIARYCODE' => $this->visitor->getExtInfoVisitor()->argc['INTERMEDIARYCODE'] ?? '',//中介人代码
            'SUBAGRTNO' => $this->visitor->getExtInfoVisitor()->argc['SUBAGRTNO'] ?? '',//子协议号
            'SALESMANCODE' => $this->visitor->getExtInfoVisitor()->argc['SALESMANCODE'] ?? '',//销售员代码
            'BUSINESSMODE' => '2',//业务方式（代理业务：2,直销为：1)
            'BUSINESSSOURCE' => $this->visitor->getExtInfoVisitor()->argc['BUSINESSSOURCE'] ?? '',//业务来源（0000直销，0100综拓业务）
            'CHANNELTIP' => $this->visitor->getExtInfoVisitor()->argc['CHANNELTIP'] ?? '',//渠道小类
            'CHANNELDETAILCODE' => $this->visitor->getExtInfoVisitor()->argc['CHANNELDETAILCODE'] ?? '',//渠道细类(渠道类型)
            'OPERATORCODE' => $this->visitor->getExtInfoVisitor()->argc['OPERATORCODE'] ?? '',//操作员代码
            'EFFECTFLAG' => intval($this->visitor->biEffectFlag or $this->visitor->ciEffectFlag),//即时起保标志，为1
            'QUTATIONNO' => '',//撤回时上报询价单号（组合险，及单险种）
            'EXPDISC' => $this->visitor->getExtInfoVisitor()->selfPricingFactor,//期望折扣，按业务要求传值
            'EPOLICYFLAG' => 'Y',//电子投保单标识，N-不启用，Y-启用
            'CLAUSETYPE' => $this->visitor->isNewEnergy ? 3 : 2,//示范条款类型:1-2014款条款；2-2020款条款；3-新能源条款
//            'OUTSYNCTYPE' => '',//交商不同步标志:1是0否
            'QUTATIONNOCI' => '',//交强险撤回询价单
            'QUTATIONNOBI' => '',//商业险撤回询价单
            'RECALLCITYPE' => '',//交强险撤回标志:1是0否
            'RECALLBITYPE' => '',//商业险撤回标志:1是0否
            'OUTOFWARRANTYTYPE' => 'Y',//启用脱保校验:Y是N否
        ];
        if($this->visitor->biEffectFlag){
            $basePart['ENDDATEBI'] = date('Y-m-d 23:59:59', strtotime($basePart['ENDDATEBI']));
        }
        return $basePart;
    }

    private function getVehicleInfo()
    {
        $carVisitor = $this->visitor->getVehicleVisitor();
        $carOwner = $this->visitor->getOwnerVisitor();
        $car = [
            'ENROLLDATE' => date('Y-m-d', strtotime($carVisitor->firstRegisterDate)),//初登日期（Sc）
            'LICENSENO' => $carVisitor->licenseNo,
            'ENGINENO' => $carVisitor->engineNo,
            'FRAMENO' => $carVisitor->vin,
            'BRANDNAME' => $carVisitor->argc['brandName'] ?? '',
            'MODELCODE' => $carVisitor->vehicleModelCode,
            'CARKINDCODE' => HBICEnums::$carKindCode[$carVisitor->carKindCode] ?? '',//车辆种类：CarKingCode（只做客车则默认：100）
            'USENATURECODE' => HBICEnums::$useNatureCode[$carVisitor->useNatureCode] ?? '',//使用性质代码：UseNatureCode（只做非营业家庭自用客车，则不用传，可以默认，如不默认，则需要三个字段）
            'ATTACHNATURE' => $carVisitor->attachNature,//所属性质
            'CARUSETYPE' => HBICEnums::$causeType[$carVisitor->causeType] ?? '',//车辆用途
            'NEGOTIATIONVALUE' => $carVisitor->actualValue ?: '0',//协商价
            'CAROWNER' => $carOwner->name,//车主
            'CREDENTIALNO' => $carOwner->certificateNo,//车主证件号码
            'CREDENTIALTYPE' => HBICEnums::$certificateTypeCode[$carOwner->certificateTypeCode] ?? '', //车主证件类型
            'LICENSEKINDCODE' => HBICEnums::$licenseTypeCode[$carVisitor->licenseTypeCode] ?? '',//号牌种类代码 Sc
            'VEHICLETYPE' => $carVisitor->vehicleStyleCode,//行驶证车辆类型代码
            'JGVEHICLETYPE' => $carVisitor->vehicleStyleCode,//交管车辆种类,不传默认K33
            'CHGOWNERFLAG' => ($carVisitor->isTransfer or $carVisitor->isCiTransfer) ? '01': '0',//过户车辆标志，没过户则默认：0；过户则为：01
            'TRANSFERDATE' => $carVisitor->transferDate,//过户日期
            'SEATCOUNT' => $carVisitor->vehicleSeat,
            'COUNTRYNATURE' => '',//国别性质
            'PURCHASEPRICE' => $carVisitor->vehiclePrice,//新车购置价
            'TONCOUNT' => $carVisitor->vehicleTonnage,//核定载质量(kg) Sc
            'EXHAUSTSCALE' => $carVisitor->vehicleExhaust,//排量 Sc
            'COMPLETEKERBMASS' => $carVisitor->wholeWeight,//整备质量(kg) Sc
            'TOTALTONCOUNT' => $carVisitor->vehicleTonnage ? round($carVisitor->vehicleTonnage / 1000, 3) : 0,//总质量(吨),当机动车种类为货车且投保交强险时，该字段必传
            'SPECIALCARFLAG' => $carVisitor->isTransfer ? '1' : '',//交强险特殊车标志，过户车必传
            'CIMODELCODE' => '',//行业车型编码, 报价返回选择车型时，必传
            'ISSUEDATE' => $carVisitor->firstRegisterDate,//发证日期 Sc
            'QUALITY' => '',//总牵引质量(KG) Sc
            'USECODE' => '',//交管使用性质 Sc
            'ISCHECKVEHICLE' => '0',//是否校验车辆信息Sc
            'PRINTBRANDNAME' => '',//打印车型厂牌型号名称
            'INSUREDTYPECODE' => $carOwner->typeCode == 'R1' ? '1' : '2',//车主类型（个人：1；团体：2）
            'GROUPCODE' => '',//团车业务编号
            'CARCHECKSTATUS' => HBICEnums::$carCheckCode[$carVisitor->carKindCode] ?? '',//验车情况
            'CARCHECKREASON' => '',//验车原因，验车情况为免验车时必传
            'CARCHECKER' => '',
            'CARCHECKTIME' => '',
            'ENERGYTYPE' => HBICEnums::$energyType[$carVisitor->energyTypeCode] ?? '',//能源类型
            'PURERANGE' => '',
            'OTHERENERGYTYPEDESC' => '',
            'MAXDESIGNSPEED' => '',
            'POWER' => '',
            'REMARK' => '',
        ];
        if ($car['CARCHECKSTATUS'] == '2') {
            $car['CARCHECKREASON'] = HBICEnums::$carCheckReasonKind[$this->visitor->getExtInfoVisitor()->carCheckReasonKind] ?? '';
            if (empty($car['CARCHECKREASON'])) {
                throw new \Exception("不支持该验车原因");
            }
        }
        if ($car['CARCHECKSTATUS'] == '3') {
            //已验车
            $car['CARCHECKER'] = $this->visitor->getExtInfoVisitor()->carChecker;
            $car['CARCHECKTIME'] = $this->visitor->getExtInfoVisitor()->carCheckDate;
        }

        return $car;
    }

    private function getPerson()
    {
        return [
            'APPNAME' => $this->visitor->getApplicantVisitor()->name,
            'APPCUSTOMERTYPE' => '00',
            'INSUREDNAME' => $this->visitor->getInsuredVisitor()->name,
            'INSUREDCUSTOMERTYPE' => '00',
            'VIPIND' => '0'
        ];
    }

    private function getKindList()
    {
        $kindList = [];

        /*** @var PremiumCoverageVisitor $item */
        foreach ($this->visitor->getCoverageVisitorList() as $key => $item) {
            $kind = [
                'ITEMKINDNO' => $key + 1,
                'KINDCODE' => HBICEnums::$coverageCode[$item->coverageCode] ?? '',
                'MODECODE' => '',
                'QUANTITY' => $item->quantity,
                'MODEL' => '0',
                'UNITAMOUNT' => $item->unitAmount,
                'AMOUNT' => round($item->amount, 2),
                'RATE' => $item->rate,
                'DEDUCTIBLEFRANCHISE' => $item->deductionRate,
                'SERVICETIMES' => $item->serviceTimes,
                'VALUE' => $item->deductionLimit
            ];
            if($item->coverageCode == 'C04001' || $item->coverageCode == 'C14001'){
                $kind['QUANTITY'] = 1;
                $kind['UNITAMOUNT'] = $kind['AMOUNT'];
            }
            //责任险填单位金额
            if($item->coverageCode == 'C05002' || $item->coverageCode == 'C15002'){
                $kind['UNITAMOUNT'] = $kind['AMOUNT'];
                $kind['AMOUNT'] = round(($this->visitor->getVehicleVisitor()->vehicleSeat - 1) * $kind['UNITAMOUNT'],2);
            }
            //必填单位金额
            if(in_array($item->coverageCode,['C04002','C14002','C13003','C03003'])){
                $kind['UNITAMOUNT'] = $kind['AMOUNT'];
            }
            if($item->coverageCode == 'C02005'){
                $kind['UNITAMOUNT'] = $kind['AMOUNT'] = '';
            }
            if($item->coverageCode == 'C01001'){
                //交强险放在头部
                $kind['AMOUNT'] = '200000';
                array_unshift($kindList,$kind);
            }else{
                $kindList[] = $kind;
            }
        }
        foreach ($kindList as $key => &$val){
            $val['ITEMKINDNO'] = $key + 1;
        }

        return $kindList;
    }

    private function getCarShipTax()
    {
        $carShipTaxVisitor = $this->visitor->getCarTaxVisitor();
        $carShipTax = [
            'TAXRELIF' => HBICEnums::$taxTypeCode[$carShipTaxVisitor->taxTypeCode] ?? '',//纳税类型代码
            'TAXNAME' => $carShipTaxVisitor->taxpayerName,//纳税人姓名
            'TAXCERTITYPE' => HBICEnums::$certificateTypeCode[$carShipTaxVisitor->taxpayerCertificateTypeCode] ?? '',//纳税人证件类型
            'TAXIDENTIFYNUMBER' => $carShipTaxVisitor->taxpayerCertificateNo,//纳税人证件号码
            'TAXPHONENUMUMBER' => $carShipTaxVisitor->taxpayerPhone,//纳税人电话号码
            'TAXPAYERIDENTIFIER' => '',//纳税人识别码
            'TOTALTONCOUNT' => $this->visitor->getVehicleVisitor()->vehicleTonnage ? round($this->visitor->getVehicleVisitor()->vehicleTonnage / 1000, 3) : 0,//总质量(吨),当机动车种类为货车且投保交强险时，该字段必传
            'TAXSTARTDATE' => $carShipTaxVisitor->taxStartDate,//纳税起期
            'TAXENDDATE' => $carShipTaxVisitor->taxEndDate,//纳税止期
            'PAID' => [
                'TAXDEPARTMENT' => '',//开具完税凭证的税务机关名称
                'TAXDOCUMENTNUMBER' => '',//完税凭证号码
                'PAIDAREACODE' => '',//开具完税凭证地区代码
                'PAIDTAXDOCUMENTDATE' => '',//完税凭证填发日期
            ],
            'DERATE' => [
                'DEDUCATIONDUECODE' => '',//减免税原因代码
                'DEDUCATIONDUETYPE' => '',//减免税方案代码
                'DEDUCATIONDUEPROPOTION' => '',//减免比例
                'DEDUCATION' => '',//减免金额
                'DEDUCATIONDOCUMENTNUMBER' => '',//减免税凭证号
                'TAXDEPARTMENT' => '',//开具减免税凭证的税务机关名称
            ],
            'FUELTYPE' => HBICEnums::$energyType[$this->visitor->getVehicleVisitor()->energyTypeCode] ?? '',
        ];

        if (!$carShipTax['TAXRELIF']) {
            throw new \Exception("不支持的缴税类型");
        }
        if (!$carShipTax['TAXCERTITYPE']) {
            throw new \Exception("不支持的证件类型");
        }
        if ($carShipTax['FUELTYPE'] === '') {
            throw new \Exception("不支持的能源类型");
        }
        if ($carShipTax['TAXRELIF'] == '03') {
            $carShipTax['PAID'] = [
                'TAXDEPARTMENT' => $carShipTaxVisitor->taxDepartment,//开具完税凭证的税务机关名称
                'TAXDOCUMENTNUMBER' => $carShipTaxVisitor->taxDepartmentCode,//完税凭证号码
                'PAIDAREACODE' => $carShipTaxVisitor->taxPaidAreaCode,//开具完税凭证地区代码
                'PAIDTAXDOCUMENTDATE' => $carShipTaxVisitor->taxDocumentDate,//完税凭证填发日期
            ];
        }
        if ($carShipTax['TAXRELIF'] == '04' || $carShipTax['TAXRELIF'] == '05') {
            $carShipTax['DERATE'] = [
                'DEDUCATIONDUECODE' => HBICEnums::$taxReductionReasonCode[$carShipTaxVisitor->taxReductionReasonCode] ?? '',//减免税原因代码
                'DEDUCATIONDUETYPE' => HBICEnums::$taxReductionCode[$carShipTaxVisitor->taxReductionCode] ?? '',//减免税方案代码
                'DEDUCATIONDUEPROPOTION' => $carShipTaxVisitor->taxFreeRate,//减免比例
                'DEDUCATION' => $carShipTaxVisitor->taxExemption,//减免金额
                'DEDUCATIONDOCUMENTNUMBER' => $carShipTaxVisitor->taxDocumentNumber,//减免税凭证号
                'TAXDEPARTMENT' => $carShipTaxVisitor->taxDepartment,//开具减免税凭证的税务机关名称
            ];
            if (empty($carShipTax['DEDUCATIONDUECODE'])) {
                throw new \Exception("不支持的减免税原因");
            }
            if (empty($carShipTax['DEDUCATIONDUETYPE'])) {
                throw new \Exception("不支持的减免税方案");
            }
        }
        return $carShipTax;
    }

    private function getChargeList()
    {
        $list = $this->visitor->getChargingPileVisitorList();
        $chargeList = [];
        /** @var PremiumChargingPileVisitor $val */
        foreach ($list as $key => $val) {
            $chargeList[] = [
                'CHARGEPILETYPE' => HBICEnums::$chargingPileKind[$val->chargingPileKind],//充电桩类型
                'CHARGINGPOSTYEARLIMIT' => HBICEnums::$chargingPileYearLimit[$val->chargingPileYearLimit],//充电桩使用年限
                'CHARGINGPOSTADDRESSTYPE' => HBICEnums::$chargingPileAddressType[$val->chargingPileAddressType],//充电桩安装地点类型
                'SERIALNO' => $key + 1,
                'CHARGINGPOSTCODE' => $val->chargingPileCode,//充电桩编码
                'CHARGINGPOSTTYPE' => $val->chargingPileType,//充电桩型号
                'INSTALLPLACE' => $val->chargingPileAddress,//充电桩地址
                'LOSSSUMINSURED' => $val->lossAmount,
                'LIABILITYSUMINSURED' => $val->liabilityAmount,
            ];
        }
        return  ['CHARGINGPOST' => $chargeList];
    }

    private function getInsuranceType()
    {
        if (!empty($this->visitor->biStartData) && !empty($this->visitor->ciStartData)) {
            return 2;
        } else {
            if (!empty($this->visitor->ciStartData)) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    public function getStaffValue(&$comCode)
    {
        $comCode = $this->visitor->getExtInfoVisitor()->argc['comCode'] ?? '';
    }

}
